// pages/answer/answer.js
import {
  getCatalogList,
  getQuestionList
} from "../../api/modules/answer.js"
import {
  login
} from "../../api/modules/login"
import localStorage from '../../utils/localStorage'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    catalogList: [], // 目录数组
    catalogTotal: 0, // 目录条数
    currentCatalog: null, // 当前目录
    swiperCatalogList: [], // 当前轮播的目录数组
    questionList: [], // 当前问题数组
    swiperQuestionList: [], // 当前轮播的问题数组
    popupState: false, // 状态
    successCount: 0, // 成功统计
    errorCount: 0, // 失败统计
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.handleLogin();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  // 登录
  handleLogin() {
    wx.login({
      success: (result) => {
        let param = {
          jsCode: result.code,
          student: -1
        }
        login(param).then((res) => {
          const {
            code,
            data
          } = res;
          if (code == 10000) {
            localStorage.set('Authorization', data.token)
            this.getCatalogData();
          }
        })
      },
    })
  },

  // 选择目录
  handleSelectCatalog(event) {
    this.setData({
      currentCatalog: event.currentTarget.dataset.item,
      popupState: false
    })
    // 再次查询数组下标数据
    this.getSwiperCatalogData();
  },

  // 查看目录
  showCatalog() {
    // 计算统计
    let successCount = 0; // 成功统计
    let errorCount = 0; // 失败统计
    this.data.catalogList.forEach(element => {
      if (element.isReply) {
        if (element.isRight) {
          successCount++;
        } else {
          errorCount++;
        }
      }
    });
    this.setData({
      successCount,
      errorCount,
      popupState: true
    })
  },

  // 关闭目录
  closeCatalog() {
    this.setData({
      popupState: false
    })
  },

  // 处理选择选项
  handleChangeOption(event) {
    let optionItem = event.currentTarget.dataset.item;
    const {
      catalogList
    } = this.data;
    // 多选
    if (optionItem.optionType == 2) {
      // 多选
      catalogList.forEach(element => {
        if (element.questionInfoDetailAid == optionItem.aid) {
          // 多选题添加选项答案
          let answerList = element.selectAnswers || [];
          answerList.push(...optionItem.value)
          element.isRight = false;
          element.isReply = false;
          element.optionType = optionItem.optionType;
          element.rightAnswers = optionItem.rightAnswers;
          element.selectAnswers = Array.from(new Set(answerList)); // 数组去重
        }
      });
      this.setData({
        catalogList
      })
      this.setQuestionResult();
    } else {
      // 单选
      catalogList.forEach(element => {
        if (element.questionInfoDetailAid == optionItem.aid) {
          element.isRight = this.arrayIncludes(optionItem.rightAnswers, optionItem.value);
          element.isReply = true;
          element.optionType = optionItem.optionType;
          element.rightAnswers = optionItem.rightAnswers;
          element.selectAnswers = optionItem.value;
        }
      });
      this.setData({
        catalogList
      })
      this.setQuestionResult();
    }
    return;
  },

  // 多选提交答案
  handleSubmitAnswer() {
    const {
      catalogList,
      currentCatalog
    } = this.data;
    catalogList.forEach(element => {
      if (element.questionInfoDetailAid == currentCatalog.questionInfoDetailAid) {
        element.isRight = this.arrayIncludes(element.selectAnswers, element.rightAnswers);
        element.isReply = true;
      }
    });
    this.setData({
      catalogList
    })
    this.setQuestionResult();
  },

  // 根据目录设置题目结果
  setQuestionResult() {
    const {
      catalogList,
      swiperQuestionList
    } = this.data;
    swiperQuestionList.forEach(element => {
      let catalogItem = catalogList.find((item) => item.questionInfoDetailAid == element.aid);
      element.isRight = catalogItem.isRight;
      element.isReply = catalogItem.isReply;
      element.rightAnswers = catalogItem.rightAnswers;
      element.selectAnswers = catalogItem.selectAnswers;
      // 设置选项状态
      element.optionData.forEach(sub => {
        sub.isSelect = this.arrayIncludes(element.selectAnswers, sub.value)
      });
    });
    this.setData({
      swiperQuestionList
    })
  },

  // 处理切换轮播项
  handleChangeSwiper(event) {
    console.log("sadsadsa");
    const {
      swiperCatalogList
    } = this.data;
    let swiperCatalogItem = swiperCatalogList.find(item => item.swiperIndex == event.detail.current)
    this.setData({
      currentCatalog: swiperCatalogItem
    })
    // 再次查询数组下标数据
    this.getSwiperCatalogData();
  },

  // 设置轮播问题数组
  setSwiperQuestionData() {
    const {
      swiperCatalogList,
      questionList
    } = this.data;
    let swiperQuestionArray = [];
    swiperCatalogList.forEach(element => {
      let questionItem = questionList.find((item) => item.aid == element.questionInfoDetailAid)
      swiperQuestionArray.push({
        ...element,
        ...questionItem,
      })
    });
    // 根据swiperIndex升序排序
    swiperQuestionArray.sort(function (a, b) {
      return a.swiperIndex - b.swiperIndex;
    });
    this.setData({
      swiperQuestionList: swiperQuestionArray
    })
    this.setQuestionResult();
  },

  // 获取问题数组
  getQuestionData() {
    const {
      swiperCatalogList
    } = this.data;
    let catalogIdList = swiperCatalogList.map(item => item.questionInfoDetailAid);
    let param = {
      questionIds: catalogIdList
    }
    getQuestionList(param).then((res) => {
      const {
        code,
        data
      } = res;
      if (code == 10000) {
        // 处理答案
        data.forEach(element => {
          if (element.options) {
            let list = [];
            let letterList = ['A', 'B', 'C', 'D', 'E', 'F', 'J', 'H']
            element.options.forEach((item, index) => {
              list.push({
                aid: element.aid, // 题号
                value: [letterList[index]], // 选项value
                label: letterList[index] + '、' + item, // 选项名称
                rightAnswers: element.answers, // 正确答案
                optionType: element.optionType, // 选项类型
                isRightOption: this.arrayIncludes(element.answers, [letterList[index]]), // 是否正确选项
                isSelect: false, // 是否选中
              })
            });
            element.optionData = list;
          }
        });
        this.setData({
          questionList: data
        })
        this.setSwiperQuestionData()
      }
    })
  },

  // 判断一个数组是否是否包含另外一个数组 largeArray（数据多的数组）smallArray（数据少的数组）
  arrayIncludes(largeArray, smallArray) {
    if (!largeArray || !smallArray) {
      return false
    } else {
      const isInclude = (arr1, arr2) => arr2.every((val) => arr1.includes(val))
      return isInclude(largeArray, smallArray); // 完全包含return true, 否则返回false
    }
  },

  // 获取轮播项题目数组
  getSwiperCatalogData() {
    const {
      currentCatalog,
      catalogList,
      catalogTotal
    } = this.data;
    let list = [];
    if (currentCatalog.index == 0) {
      // 第一条数据
      list = [catalogList[currentCatalog.index], catalogList[currentCatalog.index + 1], catalogList[currentCatalog.index + 2]]
    } else if (currentCatalog.index == catalogTotal - 1) {
      // 最后一条数据
      list = [catalogList[currentCatalog.index - 2], catalogList[currentCatalog.index - 1], catalogList[currentCatalog.index]]
    } else {
      // 中间数据
      list = [catalogList[currentCatalog.index - 1], catalogList[currentCatalog.index], catalogList[currentCatalog.index + 1]]
    }
    // 根据swiperIndex升序排序
    list.sort(function (a, b) {
      return a.swiperIndex - b.swiperIndex;
    });
    this.setData({
      swiperCatalogList: list
    })
    this.getQuestionData()
  },

  // 获取目录
  getCatalogData() {
    let param = {
      carType: "car",
      categoryType: "normal",
      subjectType: "kemu3"
    }
    getCatalogList(param).then((res) => {
      const {
        code,
        data
      } = res;
      if (code == 10000) {
        // 添加对应题号
        data.forEach((element, index) => {
          element.index = index // 题目序号
          element.swiperIndex = index % 3 // 轮播下标
          element.rightAnswers = null // 正确选项
          element.selectAnswers = null // 选择选项
          element.optionType = null // 选项类型
          element.isRight = null // 是否正确
          element.isReply = false // 是否已回答
        });
        this.setData({
          catalogList: data,
          currentCatalog: data[0],
          catalogTotal: data.length
        })
        this.getSwiperCatalogData()
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})